package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.entity.SysUser;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.db.dto.ActivityAwardDTO;
import com.fjwt.gz.db.dto.AwardScoreDTO;
import com.fjwt.gz.db.entity.ActivityAwardEntity;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.AgentScoreEntity;
import com.fjwt.gz.db.entity.AwardAgentEntity;
import com.fjwt.gz.db.entity.AwardMchEntity;
import com.fjwt.gz.db.entity.AwardScoreEntity;
import com.fjwt.gz.db.entity.AwardSettingEntity;
import com.fjwt.gz.db.vo.AwardScoreVO;
import com.fjwt.gz.db.vo.ExportAwardVO;
import com.fjwt.gz.service.mapper.AwardScoreMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 积分奖品表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardScoreService extends ServiceImpl<AwardScoreMapper, AwardScoreEntity> {


    @Autowired
    private AgentScoreService agentScoreService;
    @Autowired
    private AwardScoreService awardScoreService;
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private AwardMchService awardMchService;
    @Autowired
    private AwardAgentService awardAgentService;
    @Autowired
    private AwardSettingService awardSettingService;

    public ApiRes add(AwardScoreDTO dto, AgentInfoEntity agentInfo,SysUser sysUser) {
        AwardScoreEntity scoreAwardEntity = BeanUtil.copyProperties(dto, AwardScoreEntity.class);
        if (TextUtils.isEmpty(scoreAwardEntity.getScoreName()) || scoreAwardEntity.getScoreNum() == null) {
            return ApiRes.customFail("请求参数不全，请检查！");
        }
        if (TextUtils.isEmpty(scoreAwardEntity.getScoreName())) {
            return ApiRes.customFail("积分名称不能为空，请检查！");
        }
        if (agentInfo == null) {
            return ApiRes.customFail("所选机构不存在，请检查！");
        } else {
            LambdaQueryWrapper<AgentScoreEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AgentScoreEntity::getAgentNo,agentInfo.getAgentNo());
            queryWrapper.eq(AgentScoreEntity::getIsDefault,0);
            AgentScoreEntity entity = agentScoreService.getOne(queryWrapper);
            if(null == entity){
                return ApiRes.customFail("该机构未配置积分！");
            }
            scoreAwardEntity.setAgentScoreId(entity.getAgentScoreId());
            scoreAwardEntity.setAgentNo1(agentInfo.getAgentNo1());
            scoreAwardEntity.setAgentNo2(agentInfo.getAgentNo2());
            scoreAwardEntity.setAgentNo3(agentInfo.getAgentNo3());
            scoreAwardEntity.setAgentNo4(agentInfo.getAgentNo4());
        }

        if(null != scoreAwardEntity.getOverType() && 2== scoreAwardEntity.getOverType()){
            scoreAwardEntity.setOverTime(Utils.firstMonthLastDay());
        }

        scoreAwardEntity.setCreatedAt(new Date());
        scoreAwardEntity.setBatchNo(Utils.generateBathNo());//后端生成批次号

        long currentUserId = sysUser.getSysUserId();
        scoreAwardEntity.setCreatedUid(currentUserId);
        awardScoreService.save(scoreAwardEntity);
        AwardScoreEntity data = new AwardScoreEntity();
        BeanUtils.copyProperties(scoreAwardEntity,data);
        return ApiRes.ok(data);
    }

    /**
     * 获取列表
     * */
    public IPage<AwardScoreVO> queryList(IPage iPage, AwardScoreDTO dto) {
        AwardScoreEntity scoreAwardEntity = BeanUtil.copyProperties(dto, AwardScoreEntity.class);
        if (ObjectUtils.isNotEmpty(scoreAwardEntity.getAgentNo())) {
            scoreAwardEntity.setAgentNoList(agentInfoService.queryAllSubAgentNo(scoreAwardEntity.getAgentNo()));
            scoreAwardEntity.setAgentNo(null);
        }
        IPage<AwardScoreVO> page = baseMapper.queryList(iPage, scoreAwardEntity);
        if (ObjectUtils.isNotEmpty(page) && ObjectUtils.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(item.getAgentNo());
                if (ObjectUtils.isNotEmpty(agentInfo)) {
                    item.setAgentName(agentInfo.getAgentName());
                }
            });
        }
        return page;
    }

    /**
     * 获取列表
     * */
    public List<AwardScoreVO> queryList(AwardScoreDTO dto) {
        if (ObjectUtils.isEmpty(dto) || ObjectUtils.isEmpty(dto.getAgentNo())){
            throw new BizException("请求参数不全，请检查！");
        }
        AwardScoreEntity scoreAwardEntity = BeanUtil.copyProperties(dto, AwardScoreEntity.class);
        if (ObjectUtils.isNotEmpty(scoreAwardEntity.getAgentNo())) {
            scoreAwardEntity.setAgentNoList(agentInfoService.queryAllSubAgentNo(scoreAwardEntity.getAgentNo()));
            scoreAwardEntity.setAgentNo(null);
        }
        scoreAwardEntity.setIsConfigActivity(false);
        return this.baseMapper.queryList(scoreAwardEntity);
    }

    public ApiRes updateAwardScore(AwardScoreEntity scoreAwardEntity, AgentInfoEntity agentInfo) {
        if (scoreAwardEntity.getScoreId() == null || TextUtils.isEmpty(scoreAwardEntity.getScoreName())) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }
        if (scoreAwardEntity.getState() != null && scoreAwardEntity.getState() != Constants.AWARD_STATE.DRAFT) {
            if (TextUtils.isEmpty(scoreAwardEntity.getScoreName()) || scoreAwardEntity.getOverDays() == null
                    || scoreAwardEntity.getScoreNum() == null) {
                return ApiRes.customFail("请求参数不全，请检查！");
            }
            if (agentInfo == null) {
                return ApiRes.customFail("所选机构不存在，请检查！");
            } else {
                scoreAwardEntity.setAgentNo1(agentInfo.getAgentNo1());
                scoreAwardEntity.setAgentNo2(agentInfo.getAgentNo2());
                scoreAwardEntity.setAgentNo3(agentInfo.getAgentNo3());
                scoreAwardEntity.setAgentNo4(agentInfo.getAgentNo4());
            }

        }
        AwardScoreEntity entity = awardScoreService.getById(scoreAwardEntity.getScoreId());
        if (entity == null) {
            return ApiRes.customFail("该记录不存在！");
        }
        if (entity.getState() == Constants.AWARD_STATE.EXPIRED) {
            return ApiRes.customFail("该状态不允许修改！");
        }
        // 非草稿状态下只可增加数量
        if (entity.getState() != Constants.AWARD_STATE.DRAFT) {
            if (entity.getScoreNum() > scoreAwardEntity.getScoreNum()) {
                return ApiRes.customFail("福分数量不可小于原数量！");
            }
            entity.setScoreNum(scoreAwardEntity.getScoreNum());
            awardScoreService.updateById(entity);
            return ApiRes.ok();
        }

        if (null != scoreAwardEntity.getOverType() && 2 == scoreAwardEntity.getOverType()) {
            scoreAwardEntity.setOverTime(Utils.firstMonthLastDay());
        }

        scoreAwardEntity.setCreatedAt(null);
        scoreAwardEntity.setCreatedUid(null);
        awardScoreService.updateById(scoreAwardEntity);
        return ApiRes.ok();
    }

    public ApiRes updateState(AwardScoreEntity scoreAwardEntity) {
        Integer state = scoreAwardEntity.getState();
        Long virtualCouponId = scoreAwardEntity.getScoreId();
        if (virtualCouponId == null || state == null) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }
        AwardScoreEntity entity = awardScoreService.getBaseMapper().selectById(virtualCouponId);
        if (entity == null) {
            return ApiRes.customFail("该记录不存在！");
        }

        entity.setState(state);
        awardScoreService.updateById(entity);
        return ApiRes.ok();
    }

    public ApiRes delete(AwardScoreEntity scoreAwardEntity) {
        Long virtualCouponId = scoreAwardEntity.getScoreId();
        if (virtualCouponId == null) {
            return ApiRes.customFail("请求参数异常，请检查！");
        }
        AwardScoreEntity entity = awardScoreService.getBaseMapper().selectById(virtualCouponId);
        if (entity == null) {
            return ApiRes.customFail("该记录不存在！");
        }

        LambdaQueryWrapper<ActivityAwardEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityAwardEntity::getAwardId, virtualCouponId);
        wrapper.eq(ActivityAwardEntity::getAwardType, Constants.AWARD.SCORE);
        List<ActivityAwardEntity> list = activityAwardService.list(wrapper);
        if (!list.isEmpty()) {
            return ApiRes.customFail("该奖品已配置活动，不能删除！");
        }
        awardScoreService.removeById(virtualCouponId);
        return ApiRes.ok();
    }

    /**
     * 获取积分奖品详情
     * @param awardScoreDTO
     * @return
     */
    public AwardScoreVO detail(AwardScoreDTO awardScoreDTO) {
        if (ObjectUtils.isEmpty(awardScoreDTO.getScoreId())) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardScoreEntity awardScoreEntity = awardScoreService.getBaseMapper().selectById(awardScoreDTO.getScoreId());
        if (awardScoreEntity == null) {
            throw new BizException("该记录不存在！");
        }
        // 可核销卡券的商户
        List<AwardMchEntity> awardMchList = awardMchService.queryMchInfoByCouponId(awardScoreDTO.getScoreId(), Constants.AWARD.SCORE);
        // 分配机构数量
        List<AwardAgentEntity> awardAgentEntityList = awardAgentService.getSavedData(awardScoreDTO.getScoreId(), Constants.AWARD.SCORE);

        // 实物配置信息
        AwardSettingEntity awardSettingEntity = awardSettingService.getOne(AwardSettingEntity.gw()
                .eq(AwardSettingEntity::getAwardId, awardScoreDTO.getScoreId())
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.SCORE));

        AwardScoreVO awardScoreVO = new AwardScoreVO();
        BeanUtils.copyProperties(awardScoreEntity, awardScoreVO);
        awardScoreVO.setAwardSetting(awardSettingEntity);
        awardScoreVO.setAwardMchList(awardMchList);
        awardScoreVO.setAwardAgentList(awardAgentEntityList);
        return  awardScoreVO;
    }

    public IPage<ExportAwardVO> activityScoreDetail(IPage iPage , ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityScoreDetail(iPage, activityAwardDTO);
    }
    public List<ExportAwardVO> activityScoreDetail(ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityScoreDetail(activityAwardDTO);
    }
}
